﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Media.Imaging;
using Caliburn.Micro;
using Microsoft.Xna.Framework.Media;
using Wulong.Phone.Qiushi.i18n;
using Wulong.Phone.Utils;

namespace Wulong.Phone.Qiushi.ViewModels
{
    public class PicViewModel : BusyIndicatorViewModelBase
    {
        public PicViewModel(INavigationService navigationService)
        {
            _navigationService = navigationService;
            _imageSource = new BitmapImage();
        }

        private string _imageUrl;
        public string ImageUrl { get { return _imageUrl; } 
            set
                {
                    if(string.IsNullOrWhiteSpace(value)) return;
                    _imageUrl = value;
                    IsBusy = true;
                    _subject = ObservableResource.FromInternet(new Uri(_imageUrl.Replace("small", "large")))
                        .ObserveOnDispatcher()
                        .Finally(() => { IsBusy = false; })
                        .Subscribe(stream => ImageSource.SetSource(stream),
                            DoAfterException,
                            DoAfterCompleted);
                   // _imageSource = new BitmapImage(new Uri(_imageUrl));
                    
                } 
        }

        private static void DoAfterException(Exception ex)
        {
            MessageBox.Show(AppResources.Ex_Network_Down_Message + "\r\n" + ex.Message,
                            AppResources.Ex_Error_Title,
                            MessageBoxButton.OK);
        }

        private void DoAfterCompleted()
        {
            NotifyOfPropertyChange(() => ImageSource);
        }

        private BitmapImage _imageSource;
        public BitmapImage ImageSource
        {
            get { return _imageSource; }
            set { _imageSource = value; NotifyOfPropertyChange(() => ImageSource); }
        }


        public void GoBack()
        {
            _navigationService.GoBack();
        }

        public void SaveToMediaLibrary()
        {
            if(ImageSource==null) return;
            // Create a file name for the JPEG file in isolated storage.
            var tempJpeg = "糗事百科" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";

            // Create a virtual store and file stream. Check for duplicate tempJPEG files.
            var myStore = IsolatedStorageFile.GetUserStoreForApplication();
            if (myStore.FileExists(tempJpeg))
            {
                myStore.DeleteFile(tempJpeg);
            }

            IsolatedStorageFileStream myFileStream = myStore.CreateFile(tempJpeg);


            // Create a stream out of the sample JPEG file.
            // For [Application Name] in the URI, use the project name that you entered 
            // in the previous steps. Also, TestImage.jpg is an example;
            // you must enter your JPEG file name if it is different.
            
            var wb = new WriteableBitmap(ImageSource);

            // Encode the WriteableBitmap object to a JPEG stream.
            wb.SaveJpeg(myFileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
            myFileStream.Close();

            // Create a new stream from isolated storage, and save the JPEG file to the media library on Windows Phone.
            myFileStream = myStore.OpenFile(tempJpeg, FileMode.Open, FileAccess.Read);

            // Save the image to the camera roll or saved pictures album.
            var library = new MediaLibrary();

            
            // Save the image to the saved pictures album.
            Picture pic = library.SavePicture(tempJpeg, myFileStream);
            MessageBox.Show("成功存入相册!");

            myFileStream.Close();

            //StoreImageToMediaLibrary(ImageSource, "糗事百科" + DateTime.Now.ToString("yyyyMMddHHmmss")+".jpg");
        }

        //private MemoryStream BitmapToMemoryStream(
        //    BitmapImage bitmapImage) {
        //    if (bitmapImage == null) throw new ArgumentNullException("bitmapImage");
        //    var writeableBitmap = new WriteableBitmap(bitmapImage);
        //    using (var memoryStream = new MemoryStream())
        //    {
        //            Extensions.SaveJpeg(writeableBitmap, memoryStream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 85);
        //            memoryStream.Seek(0, SeekOrigin.Begin);     //  this is important! --> set the internal pointer to the beginning of the file        
        //            return memoryStream;
        //    }
        //    }    
        ////  this method saves an image to the medialibrary on the phone
        //public bool StoreImageToMediaLibrary(BitmapImage bitmapImage, String fileName)
        //{
        //    bool saved;
        //    var memoryStream = BitmapToMemoryStream(bitmapImage);
        //    if (memoryStream == null) return false;
        //    var library = new MediaLibrary();
        //    var exists = MediaLibraryContains(fileName);
        //    if (!exists)
        //    {
        //        library.SavePicture(fileName, memoryStream);
        //        saved = MediaLibraryContains(fileName);
        //    }
        //    else
        //    {
        //        saved = true;
        //    }        
        //    return saved;
        //}    
        ////  check to see if image is already in the medialibrary    
        //public Boolean MediaLibraryContains(String fileName)
        //{
        //    var library = new MediaLibrary();
        //    var picCollection = library.Pictures;
        //    return picCollection.Any(item => item.Name == fileName);
        //}
    }
}
